//
//  ThemeManager.m
//  kabu
//
//  Created by XiangDongMBP on 2017/4/11.
//  Copyright © 2017年 East. All rights reserved.
//

#import "ThemeManager.h"
#import <AFNetworking.h>
#import <YYCategories.h>
#import <ZipArchive.h>

NSString *const ThemeManagerUserDefThemeIdKey = @"ThemeManagerUserDefThemeIdKey";   //!< 记录当前的主题ID
NSNotificationName const ThemeManagerThemeDidChangedNotification = @"ThemeManagerThemeDidChangedNotification";  //!< 皮肤更改的通知

NSString *const ThemeManagerNavBgColor = @"navigationBarBgColor";    //!< 导航栏的背景颜色
NSString *const ThemeManagerMineBgColor= @"mineNavBarBgColor";       //!< 个人中心的背景颜色
NSString *const ThemeManagerNavTintColor = @"navigationBarTintColor";//!< 导航栏的前景颜色
NSString *const ThemeManagerTabBarTintColor = @"tabBarTintColor";           //!< 底部TabBar的前景颜色
NSString *const ThemeManagerCosSelBgColor = @"cosplayTypeSelBgColor";       //!< Cosplay页面选择cos类型的背景色
NSString *const ThemeManagerCosSelTintColor = @"cosplayTyepSelTintColot";   //!< Cosplay页面选择cos类型的蒙层颜色
NSString *const ThemeManagerMallSeaBgColor = @"mallSearchBgColor";          //!< 商城顶部搜索栏的背景色
NSString *const ThemeManagerMallSeaTextColor = @"mallSearchTextColor";      //!< 商城顶部搜索栏TextField的text的颜色
NSString *const ThemeManagerMallSeaPlaceholderColor = @"mallSearchPlaceholderColor"; //!< 商城顶部搜索栏TextField的placeholder的颜色
NSString *const ThemeManagerMallSeaTextFieldTintColor = @"mallSearchTextFieldTintColor";//!< 商城顶部搜索栏TextField的光标的颜色

@interface ThemeManager ()
@property (nonatomic, assign) NSInteger curThemeId;     //!< 当前正在试用的主题
@end

static NSString * const kThemeDirectoryName = @"Theme"; //!< Documents/Theme 皮肤存放的位置
static NSString * const kThemePropertyName = @"property.plist"; //!< 属性文件的名称

@implementation ThemeManager

+ (instancetype)sharedManager {
    static ThemeManager *sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager = [[self alloc] init];
    });
    return sharedManager;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _curThemeId = [[NSUserDefaults standardUserDefaults] integerForKey:ThemeManagerUserDefThemeIdKey];  //初始化themeID
    }
    return self;
}

- (void)setLaunchTheme {
    [self launchAppearance];
}

- (void)changeThemeWithThemeId:(NSInteger)themeId {
    if (self.curThemeId == themeId) {
        return;
    }
    
    self.curThemeId = themeId;
    // 保存到UserDefaults
    [[NSUserDefaults standardUserDefaults] setInteger:themeId forKey:ThemeManagerUserDefThemeIdKey];
    
    [self changeGlobalSkin];    // 改变外观
    [[NSNotificationCenter defaultCenter] postNotificationName:ThemeManagerThemeDidChangedNotification object:self];
}

- (BOOL)themeExistWithThemeId:(NSInteger)themeId {
    NSURL *themeUrl = [self themeUrlOfFileName:[NSString stringWithFormat:@"%zd", themeId]];
    NSString *propertyPath = [[themeUrl path] stringByAppendingPathComponent:kThemePropertyName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    return [fileManager fileExistsAtPath:propertyPath];
}

- (ThemeState)themeStateWithThemeId:(NSInteger)themeId {
    BOOL isDownload = [self themeExistWithThemeId:themeId];
    if (!isDownload) {
        return ThemeStateNotDownload;
    }
    
    return (themeId == self.curThemeId) ? ThemeStateIsUsed : ThemeStateHasDownload;
}

- (void)deleteThemeWithThemeId:(NSInteger)themeId {
    NSURL *themeUrl = [self themeUrlOfFileName:[NSString stringWithFormat:@"%zd", themeId]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:[themeUrl path]]) {
        [fileManager removeItemAtURL:themeUrl error:nil];
    }
}

- (UIImage *)themeImageWithName:(NSString *)imgName {
    if (!imgName.length) {
        return nil;
    }
    
    NSString *fileName = [[self curThemePath] stringByAppendingPathComponent:imgName];
    UIImage *image = [UIImage imageWithContentsOfFile:fileName];
    if (!image) {
        return [UIImage imageNamed:imgName];    //!< 不存在，返回默认的图片
    }
    return image;
}

- (UIColor *)themeColorWithName:(NSString *)colorName {
    NSString *curThemePath = [self curThemePath];
    NSString *propertyFilePath = [curThemePath stringByAppendingPathComponent:kThemePropertyName];
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:propertyFilePath];
    if (!dic) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"property" ofType:@"plist"];
        dic = [NSDictionary dictionaryWithContentsOfFile:path];
    }
    
    return [UIColor colorWithHexString:dic[colorName]];
}

- (void)downloadThemePackageWithThemeId:(NSInteger)themeId
                                 zipUrl:(NSString *)url
                               progress:(void (^)(NSProgress * _Nonnull))downloadProgressBlock
                      completionHandler:(void (^)(NSURLResponse * _Nonnull, NSURL * _Nullable, NSError * _Nullable))completionHandler {
    if (!url.length) {
        return;
    }
    
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:nil];
    NSURLSessionDownloadTask * downloadTask = [manager downloadTaskWithRequest:urlRequest progress:downloadProgressBlock destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        return [self themeUrlOfFileName:[response suggestedFilename]];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        NSLog(@"资源包下载到路径:%@", filePath);
        if (error) {
            if (completionHandler) {
                completionHandler(response, filePath, error);
            }
            return ;
        }
        // 下载成功，解压
        [SSZipArchive unzipFileAtPath:[filePath path] toDestination:[self themePath] overwrite:YES password:@"password" progressHandler:^(NSString * _Nonnull entry, unz_file_info zipInfo, long entryNumber, long total) {
            NSLog(@"解压进度:%zd/%zd, entry = %@", entryNumber, total, entry);
        } completionHandler:^(NSString * _Nonnull path, BOOL succeeded, NSError * _Nullable error) {
            NSLog(@"解压完成, 成功(%zd), 解压之后的路径(%@)", succeeded, path);
            if (succeeded) {
                [self deleteFileWithFilePath:path];
                NSString *srcName = [[path.lastPathComponent componentsSeparatedByString:@"."] firstObject];
                NSString *dstName = [NSString stringWithFormat:@"%zd", themeId];
                [self changeDirectoryNameForm:srcName toName:dstName];
            }
            if (completionHandler) {
                completionHandler(response, filePath, error);
            }
        }];
    }];
    // 开始下载
    [downloadTask resume];
}

#pragma mark - 更换皮肤
- (void)changeGlobalSkin {
    [self launchAppearance];
    
    // 使更改生效
    UIViewController *rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    [rootVC.view removeFromSuperview];
    [[UIApplication sharedApplication].keyWindow addSubview:rootVC.view];
}

- (void)launchAppearance {
    NSString *curThemePath = [self curThemePath];
    NSString *propertyFilePath = [curThemePath stringByAppendingPathComponent:kThemePropertyName];
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:propertyFilePath];
    if (!dic) {
        NSLog(@"读取皮肤属性plist文件失败(%@)", propertyFilePath);
        NSString *path = [[NSBundle mainBundle] pathForResource:@"property" ofType:@"plist"];
        dic = [NSDictionary dictionaryWithContentsOfFile:path];
    }
    
    // 全局更改颜色
    //UINavigationBar
    UINavigationBar *navBar = [UINavigationBar appearance];
    [navBar setBarTintColor:[UIColor colorWithHexString:dic[ThemeManagerNavBgColor]]];
    [navBar setTintColor:[UIColor colorWithHexString:dic[@"navigationBarTintColor"]]];
    UIColor *navBarTintColor = [UIColor colorWithHexString:dic[@"navigationBarTintColor"]];
    if (!navBarTintColor) {
        navBarTintColor = [UIColor whiteColor];     //!< 防止为空时，导致崩溃
    }
    NSDictionary *textAttributes = @{NSForegroundColorAttributeName: navBarTintColor,
                                     NSFontAttributeName: [UIFont systemFontOfSize:18]};
    [navBar setTitleTextAttributes:textAttributes];
    
    //UIBarButtonItem
    NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: navBarTintColor,
                                         NSFontAttributeName: [UIFont systemFontOfSize:14]};
    [[UIBarButtonItem appearance] setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
    
    // 返回的图片
    UIImage *backImg = [UIImage imageNamed:@"global_nav_back"];
    [[UIBarButtonItem appearance] setBackButtonBackgroundImage:backImg
                                                      forState:UIControlStateNormal
                                                    barMetrics:UIBarMetricsDefault];
    
    //TabBar
    [[UITabBar appearance] setTintColor:[UIColor colorWithHexString:dic[ThemeManagerTabBarTintColor]]];
    
    // UIBarItem
    NSDictionary * itemAttributes = @{NSFontAttributeName: [UIFont systemFontOfSize:9]};
    [[UIBarItem appearance] setTitleTextAttributes:itemAttributes forState:UIControlStateNormal];
}

#pragma mark - 文件操作相关
- (NSURL *)themeUrlOfFileName:(NSString *)fileName {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    //创建"Documents/Theme"目录
    NSString * themePath = [document stringByAppendingPathComponent:kThemeDirectoryName];
    BOOL isDir = NO;
    BOOL isDirExist;
    isDirExist = [fileManager fileExistsAtPath:themePath isDirectory:&isDir];
    if (!(isDirExist && isDir)) {
        BOOL bCreateDir = [fileManager createDirectoryAtPath:themePath withIntermediateDirectories:YES attributes:nil error:nil];
        if (!bCreateDir) {
            NSLog(@"Create Directory (%@) failed", themePath);
        }
    }
    
    NSString *filePath = [themePath stringByAppendingPathComponent:fileName];
    return [NSURL fileURLWithPath:filePath];
}

- (NSString *)themePath {
    NSURL *themeUrl = [self themeUrlOfFileName:@""];
    return [themeUrl path];
}

- (NSString *)curThemePath {
    NSString *themePath = [self themePath];
    return [themePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%zd", self.curThemeId]];
}

- (BOOL)deleteFileWithFilePath:(NSString *)filePath {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        return [fileManager removeItemAtPath:filePath error:nil];
    }
    return NO;
}

- (void)changeDirectoryNameForm:(NSString *)srcName toName:(NSString *)dstName {
    NSURL *srcUrl = [self themeUrlOfFileName:srcName];
    NSURL *dstUrl = [self themeUrlOfFileName:dstName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    // 如果目标已经存在，则删除
    if ([fileManager fileExistsAtPath:[dstUrl path]]) {
        if (![fileManager removeItemAtURL:dstUrl error:nil]) {
            NSLog(@"重命名文件夹已存在，删除失败");
        }
    }
    
    // 重命名文件夹
    if ([fileManager fileExistsAtPath:[srcUrl path]]) {
        NSError *error;
        BOOL suc = [fileManager moveItemAtURL:srcUrl toURL:dstUrl error:&error];
        if (!suc) {
            NSLog(@"修改文件夹名称失败, %@", error);
        }
    }
}

#pragma mark - 获取压缩包内的文件夹名称
//- (NSString *)unzipDirectoryNameWithZipPath:(NSString *)zipPath {
//    //打开文件
//    unzFile uf = unzOpen(zipPath.UTF8String);
//    //如果为空则文件不存在
//    if (NULL == uf)
//    {
//        printf("unzOpen failed...\n");
//        return;
//    }
//    //跳转到列表中第一个项
//    int err = unzGoToFirstFile(uf);
//    if (UNZ_OK != err)
//    {
//        printf("GetFileInZip unzLocateFile failed... error:%d\n",err);
//        return;
//    }
//    
//    unz_file_info file_info;
//    char filename_inzip[256];
//    //获取当前项的文件信息
//    err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0);
//    if (UNZ_OK != err)
//    {
//        printf("unzGetCurrentFileInfo failed... error:%d\n", err);
//        return ;
//    }
//    //得到文件名
//    NSString *fileName = [NSString stringWithFormat:@"%s",filename_inzip];
//}

@end
